<script>

// 代理商可新增自己所在的分组，一级分销员可新增自己的下级，代理商可删除自己所在分组，一级分销员可删除自己及下成员，二级可删除自己
// 查看可以放开，在查看页面的提现按钮只有自己可见，同时也是绑定的
import {
    getDistributionUsersTree,
    deleteDistributionUser,
    disableDistributionUser,
    distributionRegister
} from "@/api/user"


export default {
    data() {
        return {
            tableData: {
                records: [],
                current: 1,
                size: 10,
                total: 0
            },
            drawer: false,
            selectRow: null,
            loading: false,
            loginForm: {
                name: "",
                password: "",
                username: "",
                mobile: "",
                roleIds: ["distributer"],
                parentId: "",
                code: ""
            },
            rules: {
                name: [
                    {required: true, message: "请输入用户名", trigger: "blur"},
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"}
                ],
                username: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "请输入用户名"
                    }
                ],
                mobile: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "请输入手机号"
                    }
                ]
            }
        }
    },
    created() {
        this.getTableData()
    },

    methods: {
        getTableData() {
            getDistributionUsersTree({
                current: this.tableData.current,
                size: this.tableData.size
            }).then(res => {
                this.tableData = res
            });
        },
        deleteUser(row) {
            this.$confirm("确定要删除该用户吗？", "提示", {}).then(_ => {
                disableDistributionUser(row.id).then(_ => {
                    this.$message.success("删除成功")
                    this.getTableData()
                })
            }).catch(_ => {

            })
            // ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
            //     confirmButtonText: "确定",
            //     cancelButtonText: "取消",
            //     type: "warning"
            // }).then(async () => {
            //     try {
            //         await axios.delete(`/api/users/${row.id}`)
            //         ElMessage.success("删除成功")
            //         fetchData()
            //     } catch (error) {
            //         ElMessage.error("删除失败")
            //     }
            // })
        },
        addUser(row) {
            this.selectRow = row;
            // 这里可以打开一个表单对话框来添加新用户
            // 允许代理商与一级分销员添加
            if (this.$store.state.currentUser.apiRoleName === "distributer") {
                if (this.$store.state.currentUser.id === row.id) {
                    //     弹出弹框进行添加
                    this.drawer = true;
                } else {
                    this.$message.error("只能添加自己所属下级")
                }
            } else {
                // 只能添加自己所在分组
                if (this.isInMyGroup(row)) {
                    this.drawer = true;
                } else {
                    this.$message.error("只能添加自己所属下级")
                }
            }
        },
        currentChange(val) {
            this.tableData.current = val;
            this.getTableData()
        },
        //     判断是否在自己所在分组
        isInMyGroup(data) {
            let currentUser = this.$store.state.currentUser;
            if (currentUser.distributionLevel === null) {
                for (let i = 0; i < this.tableData.records.length; i++) {
                    if (this.tableData.records[i].id === currentUser.id) {
                        if (data.levelsId === null) {
                            return currentUser.id === data.id;
                        } else if (data.levelsId === 1) {
                            return data.parentId === currentUser.id;
                        } else if (data.levelsId === 2) {
                            for (let j = 0; j < this.tableData.records[i].children; j++) {
                                if (this.tableData.records[i].children[j].id === data.parentId) {
                                    return true;
                                }
                            }
                            return false;
                        }
                    }
                }
            } else {
                if (data.levelsId === 1) {
                    return data.id === currentUser.id;
                } else {
                    // 如果data是二级分销
                    for (let i = 0; i < this.tableData.records.length; i++) {
                        for (let j = 0; j < this.tableData.records[i].children; j++) {
                            if (this.tableData.records[i].children[j].id === data.parentId) {
                                return data.parentId === currentUser.id;
                            }
                        }

                    }
                    return false;
                }
            }
        },
        drawClosed() {
            this.selectRow = null;
        },
        submit() {
            this.$refs.loginForm.validate(valid => {
                if (!valid) return;
                //    发起请求，并重新拉取数据
                this.loading = true;
                distributionRegister({
                    ...this.loginForm,
                    isAddDistributer: true,
                    recommendUserId: this.selectRow.id
                }).then(res => {
                    this.drawer=false;
                    this.getTableData()
                }).finally(
                    () => {
                        this.loading = false;
                    }
                )
            });
        }
    }
}
</script>

<template>
    <div class="users-container">
        <el-table :data="tableData.records" row-key="id" border>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column label="分销等级">
                <template slot-scope="scope">
                    {{ scope.row.levelName || "代理商" }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="deleteUser(scope.row)">删除</el-button>
<!--                    <el-button-->
<!--                        v-if="scope.row.levelsId!==2&&(!$store.state.currentUser.distributionLevel||($store.state.currentUser.distributionLevel===1))"-->
<!--                        v-permission="['distribution:users:add']" type="text" size="small" @click="addUser(scope.row)">-->
<!--                        新增-->
<!--                    </el-button>-->
                    <el-button
                      type="text" size="small" @click="addUser(scope.row)">
                        新增
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            :current-page.sync="tableData.current"
            :page-sizes="[10]"
            :page-size.sync="tableData.size"
            layout="total,  prev, pager, next, sizes, jumper"
            :total="tableData.total"
            @current-change="currentChange"
        >
        </el-pagination>
        <el-dialog :visible.sync="drawer" title="新增分销员" @closed="drawClosed">
            <el-form
                ref="loginForm"
                :model="loginForm"
                class="login-form yx-str"
                autocomplete="off"
                label-position="left"
                :rules="rules"
            >
                <el-form-item prop="username" label="用户名">
                    <el-input
                        v-model="loginForm.username"
                        placeholder="请输入用户名"
                        name="username"
                        type="text"
                        tabindex="1"
                        autocomplete="off"
                    />
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input
                        v-model="loginForm.password"
                        placeholder="请输入密码"
                        name="password"
                        type="password"
                        tabindex="2"
                        autocomplete="off"
                    />
                </el-form-item>
                <el-form-item prop="name" label="昵称">
                    <el-input
                        v-model="loginForm.name"
                        placeholder="请输入昵称"
                        name="name"
                        type="text"
                        tabindex="3"
                        autocomplete="off"
                    />
                </el-form-item>
                <el-form-item prop="mobile" label="手机号">
                    <el-input
                        v-model="loginForm.mobile"
                        placeholder="请输入手机号"
                        name="mobile"
                        type="text"
                        tabindex="4"
                        autocomplete="off"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button
                        :loading="loading"
                        type="primary"
                        style="width:100%;height:50px;margin-top: 40px; font-size: 20px;"
                        size="default"
                        @click="submit"
                    >添加
                    </el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<style scoped lang="scss">
// 样式可以根据需要进行调整
.users-container{
    margin: 20px;
}
</style>
